import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState, AppThunk } from "../app/store";
import { loginApi } from "../http/api/userApi";
import type { UserLoginProps } from "../http/types";

export interface userState {
  userId: string | number | null;
  username: string | null;
  token: string | null;
}

const initialState: userState = {
  userId: sessionStorage.getItem("userId"),
  username: sessionStorage.getItem("username"),
  token: sessionStorage.getItem("token"),
};

export const loginAsync = createAsyncThunk(
  "user/loginAction",
  async (params: UserLoginProps) => {
    const loginRes = await loginApi(params);
    console.log("登录接口", loginRes.data);

    if (loginRes.data.code === "200") {
      return loginRes.data.data;
    } else {
      return Promise.reject(loginRes.data);
    }
  }
);

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    logout(state) {
      state.userId = null;
      state.username = "";
      state.token = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(loginAsync.pending, (state) => {
        console.log("user - login - loading");
      })
      .addCase(loginAsync.fulfilled, (state, action) => {
        console.log("user - login - fulfilled", state, action);
        state.userId = action.payload.userId;
        state.username = action.payload.username;
        state.token = action.payload.token;

        sessionStorage.setItem("userId", action.payload.userId);
        sessionStorage.setItem("username", action.payload.username);
        sessionStorage.setItem("token", action.payload.token);
      })
      .addCase(loginAsync.rejected, (state) => {
        console.log("user - login - rejected", state);
      });
  },
});

export const { logout } = userSlice.actions;

export default userSlice.reducer;
